package com.swotxu.mall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.swotxu.common.constant.CartConstant;
import com.swotxu.common.utils.R;
import com.swotxu.common.vo.SkuInfoVo;
import com.swotxu.mall.cart.feign.ProductFeignService;
import com.swotxu.mall.cart.interceptor.CartInterceptor;
import com.swotxu.mall.cart.service.CartService;
import com.swotxu.mall.cart.vo.Cart;
import com.swotxu.mall.cart.vo.CartItem;
import com.swotxu.mall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    /**
     * 登陆用户购物车：CartConstant.REDIS_KEY_PREFIX + UserId
     * 未登陆用户购物车：CartConstant.REDIS_KEY_PREFIX + UserKey
     *
     * @param suffix UserId / UserKey
     */
    private String getRedisKeyCart(Object suffix) {
        return CartConstant.REDIS_KEY_PREFIX + suffix;
    }

    /**
     * 获取指定购物车的所有商品
     *
     * @param key 购物车 key
     * @return 购物车记录
     */
    private List<CartItem> getCartItems(String key) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(key);
        return Optional.ofNullable(hashOps.values())
                .map(objs -> objs.stream().map(String::valueOf).map(str -> JSON.parseObject(str, CartItem.class)).collect(Collectors.toList()))
                .orElseGet(Collections::emptyList);
    }

    /**
     * 获取到我们要操作的购物车
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //gulimall:cart:1
        String cartKey = userInfoTo.getUserId() != null ? getRedisKeyCart(userInfoTo.getUserId())
                : getRedisKeyCart(userInfoTo.getUserKey());
        return redisTemplate.boundHashOps(cartKey);
    }

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            //若购物车无此商品，添加新商品到购物车
            //1、远程查询当前要添加的商品的信息
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getValue("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(data.getPrice());
            }, executor);

            //2、远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);
            // 等待任务执行完成
            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();

            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }
        //购物车有此商品，修改数量
        CartItem cartItem = JSON.parseObject(res, CartItem.class);
        cartItem.setCount(cartItem.getCount() + num);
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
        return cartItem;
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(str, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            // 1、若用户登录
            String cartKey = getRedisKeyCart(userInfoTo.getUserId());   // 登陆用户购物车 key
            String tempCartKey = getRedisKeyCart(userInfoTo.getUserKey()); // 未登陆用户购物车 key
            // 如果临时购物车的数据还没有进行合并【合并购物车】
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            for (CartItem item : tempCartItems) {
                addToCart(item.getSkuId(), item.getCount());
            }
            // 清除临时购物车的数据
            clearCart(tempCartKey);
            // 获取登录后的购物车的数据【包含合并过来的临时购物车的数据，和登录后的购物车的数据】
            cart.setItems(getCartItems(cartKey));
        } else {
            // 2、没登录
            String tempCartKey = getRedisKeyCart(userInfoTo.getUserKey());
            //获取临时购物车的所有购物项
            cart.setItems(getCartItems(tempCartKey));
        }
        return cart;
    }

    @Override
    public void clearCart(String cartkey) {
        redisTemplate.delete(cartkey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() == null){
            return Collections.emptyList();
        }
        List<CartItem> cartItems = getCartItems(getRedisKeyCart(userInfoTo.getUserId()));

        // 远程批量获取所有被选中的购物项 sku最新价格
        List<Long> skuIds = cartItems.stream().filter(CartItem::getCheck).map(CartItem::getSkuId).collect(Collectors.toList());
        R res = productFeignService.batchGetPrice(skuIds);
        Map<Long, BigDecimal> skuIdPriceMap = Optional.ofNullable(res)
                .filter(R::isOk).map(r -> r.getData(new TypeReference<Map<Long, BigDecimal>>() {}))
                .orElseGet(Collections::emptyMap);
        // 更新价格
        return cartItems.stream()
                .filter(CartItem::getCheck)
                // 更新最新价格
                .peek(item -> item.setPrice(skuIdPriceMap.getOrDefault(item.getSkuId(), item.getPrice())))
                .collect(Collectors.toList());
    }
}
